#!/bin/bash
echo "===== 开始系统调优 ====="
# 记录开始时间
start_time=$(date +%s.%N)
# 设置日志文件路径和权限
LOG_FILE=/var/log/system_optimization.log
touch $LOG_FILE
chmod 640 $LOG_FILE
# 磁盘空间优化
echo "===== 开始处理磁盘空间问题 ====="
du -sh / | awk '$1 >= "500M" && $2 ~ "/$" {print $0}' >> $LOG_FILE
df --human-readable /var/log/ >> $LOG_FILE
# 磁盘I/O调优（适用于SSD）
echo "fs.aio_max_nr=16384" >> /etc/sysctl.conf
sysctl -p
# 调整文件句柄限制
cpulimit --pid $(pgrep logstash) --cpu 2
tuned profile latency-performance
# 权限问题检查与修复
echo "===== 检查Logstash日志权限 ====="
ls -l /var/log/logstash/ | grep denied >> $LOG_FILE
chown -R logstash:logstash /var/log/logstash/
chmod -R 755 /var/log/logstash/
# 收集指标
disk_usage=$(df -h /var/log/)
io_stats=$(iostat -d -k | grep sda)
cpu_usage=$(top -n1 | awk '/Cpu/ {print $2}')
memory_usage=$(free -m)
# 记录结束时间
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time" | bc)
# 结构化输出和日志记录
echo "===== 调优摘要 ====="
echo "总执行时间: ${duration}秒"
echo "磁盘使用情况: ${disk_usage}"
echo "I/O统计: ${io_stats}"
echo "CPU使用率: ${cpu_usage}%"
echo "内存使用量: ${memory_usage}"
# 结构化输出
echo "===== 性能指标 ====="
echo '{
    "total_time": "'$duration'",
    "disk_usage": "'$disk_usage'",
    "io_statistics": "'$io_stats'",
    "cpu_usage": "'$cpu_usage'",
    "memory_usage": "'$memory_usage'"
}'
# 错误处理和退出
if [ $? -ne 0 ]; then
    echo "脚本执行过程中发生错误，请检查日志文件 $LOG_FILE"
fi
echo "===== 调优完成 ====="